/**
 * Created by zhang_renyang on 15/1/4.
 */
var dateUtils = require('../utils/dateUtils');
var articleModel = require('../schema/article');
var Reply = require('../model/reply');

function Article(article){
    this.articleTitle = article.articleTitle;
    this.functionDescription = article.functionDescription;
    this.articleExamples = article.articleExamples;
    this.jobInterview=article.jobInterview;
    this.is_recommend = article.is_recommend;
    this.order_by = article.order_by;
    this.user_id = article.user_id;
    this.category_id = article.category_id;
}
//保存数据
Article.prototype.save = function(callback){
    var newArticle = new articleModel({
        articleTitle:this.articleTitle,
        functionDescription:this.functionDescription,
        articleExamples:this.articleExamples,
        jobInterview:this.jobInterview,
        is_recommend:this.is_recommend,
        order_by:this.order_by,
        user_id:this.user_id,
        category_id:this.category_id,
        create_time:dateUtils.getTime(),
        update_time:dateUtils.getTime()
    });

    newArticle.save(function(err,article){
        if(err)
            callback(err);
        else
        callback(null,article);
    });
}

Article.prototype.update = function(_id,callback) {
    //要存入数据库的用户信息文档
    var article = {
        articleTitle:this.articleTitle,
        functionDescription:this.functionDescription,
        articleExamples:this.articleExamples,
        jobInterview:this.jobInterview,
        is_recommend:this.is_recommend,
        order_by:this.order_by,
        category_id:this.category_id,
        update_time:dateUtils.getTime()
    };
    articleModel.update({_id:_id},article,function(err,article){
        if(err)
            return callback(err);
        else
            callback(null,article);
    });
};

Article.findById = function(_id,callback){
    articleModel.findOne({_id:_id},null,{}).populate('user_id').populate('category_id').exec(function(err,article){
        if(err)
            callback(err);
        else{
            Reply.findByTopicId(_id,function(err,replies){
                article.replies = replies;
                callback(err,article);
            });
        }
    });
}

Article.deleteById = function(_id,callback){
    articleModel.remove({_id:_id}, function(err){
        callback(err);
    });
}

Article.pageQuery = function(query,pageInfo,callback){
    articleModel.count(query,function(err,count){
        articleModel.find(query,null,{}).sort({order_by:-1}).skip((pageInfo.pageNum-1)*pageInfo.pageSize).limit(pageInfo.pageSize).populate('user_id').populate('category_id').exec(function(err,articles){
            if(err){
                callback(err);
            }else{
                callback(null,count,articles);
            }
        });
    });
}


module.exports= Article;